package com.xsomnus.open.im.auth;

import com.xsomnus.open.im.protocol.Packet;
import com.xsomnus.open.im.protocol.codec.PacketCodec;
import com.xsomnus.open.im.protocol.request.LoginRequestPacket;
import com.xsomnus.open.im.protocol.request.MessageRequestPacket;
import com.xsomnus.open.im.protocol.response.LoginResponsePacket;
import com.xsomnus.open.im.protocol.response.MessageResponsePacket;
import com.xsomnus.open.im.util.PrintUtils;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import java.util.HashMap;
import java.util.Map;

/**
 * @author @xsomnus666_xiawenye★
 * @since 2019/4/24 0024 18:30
 * 当你发现自己的才华撑不起野心时，就请安静下来学习吧
 */
public class AuthServerHandler extends ChannelInboundHandlerAdapter {

    private final static Map<String, String> usernameMap;

    static {
        usernameMap = new HashMap<>(2 << 2);
        usernameMap.put("xsomnus666", "123456");
        usernameMap.put("jackson", "654321");
    }


    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {

        ByteBuf requestByteBuf = (ByteBuf) msg;
        Packet packet = PacketCodec.INSTANCE.decode(requestByteBuf);
        System.out.println("packet: " + packet);
        if (packet instanceof LoginRequestPacket) {
            PrintUtils.print("收到客户端登录请求");
            // 登陆对象
            LoginRequestPacket loginRequestPacket = (LoginRequestPacket) packet;
            LoginResponsePacket loginResponsePacket = new LoginResponsePacket();
            loginResponsePacket.setVersion(packet.getVersion());
            if (validate(loginRequestPacket)) {
                loginResponsePacket.setSuccess(true);
                PrintUtils.print(loginRequestPacket.getUsername() + "登陆成功");
            } else {
                loginResponsePacket.setSuccess(false);
                loginResponsePacket.setReason("账号密码校验失败");
                PrintUtils.print(loginRequestPacket.getUsername() + "登陆失败");
            }
            // 登陆响应
            ByteBuf responseByteBuf = PacketCodec.INSTANCE.encode(ctx.alloc(), loginResponsePacket);
            ctx.channel().writeAndFlush(responseByteBuf);
        } else if (packet instanceof MessageRequestPacket) {
            // 客户端发送消息
            MessageRequestPacket requestPacket = (MessageRequestPacket) packet;
            MessageResponsePacket responsePacket = new MessageResponsePacket();
            PrintUtils.print("收到来自客户端的消息: " + requestPacket.getMessage());
            responsePacket.setMessage("服务端回复【" + requestPacket.getMessage() + "】");
            ByteBuf responseByteBuf = PacketCodec.INSTANCE.encode(ctx.alloc(), responsePacket);
            ctx.writeAndFlush(responseByteBuf);
        }
    }

    private boolean validate(LoginRequestPacket loginRequestPacket) {
        return usernameMap.get(loginRequestPacket.getUsername()).equals(loginRequestPacket.getPassword());
    }

}

